/**
 * ZHU framework. Copyright 2012-, all rights reserved.
 *
 * $Id: StaffServiceImpl.java 47 2012-09-20 06:31:35Z zhuxiaopeng $
 * $Revision: 47 $
 * $Date: 2012-09-20 14:31:35 +0800 (四, 2012-09-20) $
 * $Author: zhuxiaopeng $
 */
package daily.service;

import java.util.*;

import javax.ejb.*;
import javax.persistence.*;

import zhu.framework.entity.*;
import zhu.framework.service.*;
import daily.entity.*;

/**
 * <p>
 * </p>
 * 
 * @author $Author: zhuxiaopeng $
 * @version $Revision: 47 $ - $Date: 2012-09-20 14:31:35 +0800 (四, 2012-09-20) $
 */
@Stateless
public class StaffServiceImpl extends AbstractPersistenceOperationService {
	public List<Staff> getStaffList() {
		final StaffLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffLifecycle.class);
		return lifecycle.findAll();
	}

	public Staff getStaff(final EntityId id) {
		final StaffLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffLifecycle.class);
		return lifecycle.findById(id);
	}

	public Staff saveStaff(final Staff selectStaff) {
		checkInput(selectStaff);
		final StaffLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffLifecycle.class);
		try {
			if (selectStaff.getEntityId() != null) {
				return lifecycle.update(selectStaff, null);
			} else {
				return lifecycle.create(selectStaff);
			}
		} catch (final OptimisticLockException e) {
			throw new BusinessException(e.getMessage());
		}
	}

	public void deleteStaff(final Staff selectStaff) {
		removeAllDaily(selectStaff);
		final StaffLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffLifecycle.class);
		lifecycle.remove(selectStaff);
	}

	private void removeAllDaily(final Staff selectStaff) {
		final DailyLifecycle lifecycle = getLifecycleFactory().getLifecycle(DailyLifecycle.class);
		final List<Daily> allDaily = lifecycle.findByStaff(selectStaff);
		lifecycle.removeAll(allDaily);
	}

	private void checkInput(final Staff selectStaff) {
		final StaffLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffLifecycle.class);
		final Staff findStaff = lifecycle.findByUserName(selectStaff.getUserName());
		if (findStaff != null && findStaff.getEntityId().equals(selectStaff.getEntityId()) == false) {
			throw new BusinessException(new BusinessServiceMessage("ログイン名は他の人が使っています。"));
		}
	}

}
